$(document).ready(function() {
    var $url = $('body').attr('data-siteurl');
    getTools(1);

    $.ajax({
        url: $url + 'get-tools',
        type: 'post',
        data: {'tool-type': 1},
        dataType: "json",
        success: function(data) {
            $("#reload-img-con").text("");
            $("#reload-img-con").append(data);
            updateSubLayout();
            reload_sub_stage();
        }
    });

    function updateTooltip(tooltip, x, y, text) {
        tooltip.getText().setAttr("text", text);
        tooltip.setAttr("position", {x: x, y: y});
        tooltip.show();
    }

    function canvasToJSON() {
        return floorStage.toJSON();
    }

    function uniqueID() {
        return Math.floor((1 + Math.random()) * 0x1000);
    }
    
    $("#single-floor").on("mousedown touchstart",function(){
        $.ajax({
             url: $url + 'save-single-floor',
            type: 'post',
            data: {'ev-id': $('#view-event-calendar-popup #event-id').val()},
            dataType : "json",
            success : function(data){
                if(data === "pagSuccess"){
                    $("#sub-layout-id").val(uniqueID());
                    //$("#sub-layout-id").val(uniqueID());
                    $("#venue-sub-container").css("display", "block");
                    $("#venue-main-container").css("display", "none");
                    $("#main-toolbar").css("display", "none");
                    $("#sub-toolbar").removeClass("hide");
                    newOrReloadStage();
                }
                
            }
        });
    });

    function saveLayout() {
        $("#imgData").val(canvasToJSON());
        $("#ev-id").val($('#view-event-calendar-popup #event-id').val());
        var formData = new FormData($("#ven")[0]);
        var request = new XMLHttpRequest();
        request.open("POST", $url + "save-layout");
        request.send(formData);
    }

    function newOrReloadStage() {
        $.ajax({
            url: $url + 'has-layout',
            type: 'post',
            data: {'ev-id': $('#view-event-calendar-popup #event-id').val()},
            dataType: "json",
            success: function(data) {
                $("#venue-sub-container").css("display", "none");
                $("#venue-tab").css("display", "block");
                //alert(data);
                if (data.status === 0) {
                    $("#venue-main-container").css("display", "block");
                    $("#main-toolbar").removeClass("hide");
                    $("#reload-main-toolbar").addClass("hide");
                }else if(data.status === 1){
                    $("#reload-venue-main-container").css("display", "block");
                    $("#main-toolbar").addClass("hide");
                    $("#reload-main-toolbar").removeClass("hide");
                } else {
                    $("#reload-sub-layout-id").val()
                    getSubData();
                    $("#main-toolbar").addClass("hide");
                    $("#reload-main-toolbar").addClass("hide");
                }
            }
        });

        $.ajax({
            url: $url + "reload-layout",
            type: "post",
            data: {'ev-id': $('#view-event-calendar-popup #event-id').val()},
            dataType: "json",
            success: function(data) {
                $("#imgData").val(data.imgData);
                $("#img-url").val(data.imgUrl);
                reload_stage();
            }
        });
    }

    //venue-tab clicked
    $("#modal-event-calendar li:eq(4) a").on('mousedown touchstart', function() {
        $("#reload-venue-sub-container").addClass("hide");
        $("#reload-sub-toolbar").addClass("hide");
        newOrReloadStage();
    });

    $("#modal-event-calendar li:not(:eq(4)) a").on('mousedown touchstart', function() {
        $("#venue-tab").css("display", "none");
    });

    /*------------------------*/
    var checkRotate = 0;
    var checkDrawRect = 0;
    var checkEditLabel = 0;
    var removeFloorChecker = 0;
    var floorDrawChecker = 0;
    var mTop = 0, mBottom = 0, mUp = 0, mDown = 0;
    var checkRemoveImg = 0;

    //storage of the pentagon points (array)
    var pentPoints = [];
    var tempPoints = "";
    var floorStage = new Kinetic.Stage({
        container: "venue-main-working-area",
        width: (window.innerWidth / 100) * 44,
        height: 420
    });
    var tooltipLayer = new Kinetic.Layer();
    var tempLayer = new Kinetic.Layer();
    var coordImgLayer = new Kinetic.Layer();
    var lineLayer = new Kinetic.Layer();
    floorStage.add(coordImgLayer);
    var tooltip = new Kinetic.Label({
        opacity: 0.75,
        visible: false,
        listening: false,
        name: "tp"
    });

    tooltip.add(new Kinetic.Tag({
        fill: 'black',
        pointerDirection: 'down',
        pointerWidth: 10,
        pointerHeight: 10,
        lineJoin: 'round',
        shadowColor: 'black',
        shadowBlur: 10,
        shadowOffset: {x: 10, y: 10},
        shadowOpacity: 0.5
    }));

    tooltip.add(new Kinetic.Text({
        text: '',
        fontFamily: 'Calibri',
        fontSize: 18,
        padding: 5,
        fill: 'white'
    }));

    tooltipLayer.add(tooltip);
    //converts the canvas to JSON
    $("#edit-label").on('mousedown touchstart', function(e) {
        
        if(checkEditLabel === 0){
            checkEditLabel = 1;
            removeFloorChecker = 0;
            $("#edit-label").addClass("btn-success");
            $("#edit-label").removeClass("btn-default");
            $("#cancel-remove").addClass("disabled");
            $("#remove-floor").removeClass("disabled");
        }else{
            $("#edit-label").addClass("btn-success");
            $("#edit-label").removeClass("btn-default");
            checkEditLabel = 0;
        }

        
    });

    //Set the img uploaded into coorWorkingAre
    $("#main-layout-img").change(function() {
        $("#floor-draw").removeClass("disabled");
        $("#show-floors").removeClass("disabled");
        $("#floor-draw").on('mousedown touchstart', function() {
            if (floorDrawChecker === 0) {
                floorDrawChecker = 1;
                floorStage.add(lineLayer);
                floorStage.add(tempLayer);
                $("#floor-draw").addClass("disabled");
            } else {
                floorDrawChecker = 0;
                pentPoints.length = 0;
            }
        });

        var coordImg = new Kinetic.Image({
            draggable: false,
            width: (window.innerWidth / 100) * 44,
            height: 420,
            name: "coordBG"
        });

        coordImgLayer.add(coordImg);
        image = new Image();

        if (this.files && this.files[0]) {
            var reader = new FileReader();

            reader.onload = function(e) {
                image.src = e.target.result;
            };
            reader.readAsDataURL(this.files[0]);
        }

        image.onload = function() {
            coordImg.setImage(image);
            coordImgLayer.draw();
        };
        window.onresize = function(event) {
            floorStage.setWidth((window.innerWidth / 100) * 44);
            coordImgLayer.setWidth((window.innerWidth / 100) * 44);
        };
    });

    $("#venue-main-working-area").on('mousedown touchstart', function(e) {
        if (floorDrawChecker === 1) {
            var mouseX = e.pageX - $("#venue-main-working-area").offset().left;
            var mouseY = e.pageY - $("#venue-main-working-area").offset().top;

            pentPoints.push(mouseX + "," + mouseY);

            tempPoints = "[";
            for (var x = 0; pentPoints.length > x; x++) {
                if (x === 0) {
                    tempPoints += "[" + pentPoints[x] + "]";

                    var circ = new Kinetic.Circle({
                        x: mouseX,
                        y: mouseY,
                        stroke: 'red',
                        fill: 'white',
                        strokeWidth: 1.5,
                        radius: 2,
                        name: "circ"
                    });
                    lineLayer.add(circ);
                    lineLayer.draw();
                } else {
                    tempPoints += ",[" + pentPoints[x] + "]";
                }
            }
            tempPoints += "]";
            tempPoints = JSON.parse(tempPoints);
            $(this).on('mousemove touchstart', function(eventM) {
                var mx = eventM.pageX - $("#venue-main-working-area").offset().left;
                var my = eventM.pageY - $("#venue-main-working-area").offset().top;
                var tempMovePoints = "[[" + mouseX + "," + mouseY + "]," + "[" + mx + "," + my + "]]";
                tempMovePoints = JSON.parse(tempMovePoints);

                var tempLine = new Kinetic.Line({
                    points: tempMovePoints,
                    stroke: "black",
                    strokeWidth: 2,
                    lineCap: "round",
                    lineJoin: "round"
                });
                tempLayer.destroyChildren();
                tempLayer.add(tempLine);
                tempLayer.batchDraw();
            });

            var line = new Kinetic.Line({
                points: tempPoints,
                stroke: "black",
                strokeWidth: 2,
                lineCap: "round",
                lineJoin: "round",
                name: "line"
            });
            lineLayer.add(line);
            lineLayer.draw();

            if (tempPoints.length >= 3) {
                $("#finish-draw").removeClass("disabled");
            }
        }
    });

    $("#remove-floor,#reload-remove-floor").on('mousedown touchstart', function() {
        removeFloorChecker = 1;
        checkEditLabel = 0;
        $("#remove-floor").addClass("disabled");
        $("#cancel-remove").removeClass("disabled");
        $("#reload-remove-floor").addClass("disabled");
        $("#reload-cancel-remove").removeClass("disabled");
    });

    $("#cancel-remove,#reload-cancel-remove").on('mousedown touchstart', function() {
        removeFloorChecker = 0;
        $("#cancel-remove").addClass("disabled");
        $("#remove-floor").removeClass("disabled");
        $("#reload-cancel-remove").addClass("disabled");
        $("#reload-remove-floor").removeClass("disabled");
    });
    

    $("#finish-draw").on('mousedown touchstart', function(e) {
        $("#finish-draw").addClass("disabled");
        $("#floor-draw").removeClass("disabled");
        var unq = uniqueID();
        tempLayer.destroyChildren();
        tempLayer.destroy();
        lineLayer.destroyChildren();
        var poly = new Kinetic.Polygon({
            points: tempPoints,
            fill: "yellow",
            opacity: .2,
            name: "polygon",
            id: unq
        });
        poly.setAttr("tooltip-label", "Default");
        poly.setAttr("tooltip-desc", "Description (click edit label to change)");
        coordImgLayer.add(poly);
        coordImgLayer.draw();
        floorDrawChecker = 0;
        pentPoints.length = 0;
        lineLayer.remove();

        poly.on('mouseover touchstart', function() {
            this.setOpacity(.285);
            coordImgLayer.draw();
            document.body.style.cursor = 'pointer';
            floorStage.add(tooltipLayer);
            if ($("#floor-label").hasClass("hide") && $("#floor-desc").hasClass("hide")) {
                $("#displayed-label").removeClass("hide");
                $("#displayed-desc").removeClass("hide");
                $("#displayed-label").text(this.getAttr("tooltip-label"));
                $("#displayed-desc").text(this.getAttr("tooltip-desc"));
            }
        });

        poly.on('mousemove', function(e) {
            var el = this;
            updateTooltip(tooltip, e.pageX - $("#venue-main-working-area").offset().left, e.pageY - $("#venue-main-working-area").offset().top, el.getAttr("tooltip-label"));
            tooltipLayer.batchDraw();
        });

        poly.on('mouseout touchend', function() {
            document.body.style.cursor = 'default';
            this.setOpacity(0);
            coordImgLayer.draw();
            //floorStage.remove(tooltipLayer);
            tooltip.hide();
            $("#displayed-label").addClass("hide");
            $("#displayed-desc").addClass("hide");
        });

        poly.on('mousedown touchstart', function(e) {
            var tmp = this;
            if (removeFloorChecker === 1) {
                this.remove();
            } else {
                if (checkEditLabel === 1) {
                    $("#floor-label").removeClass("hide");
                    $("#floor-desc").removeClass("hide");
                    $("#label-save").removeClass("hide");
                    $("#floor-label").val(tmp.getAttr("tooltip-label"));
                    $("#floor-desc").val(tmp.getAttr("tooltip-desc"));
                    var la = document.getElementById("label-save");
                    console.log(tmp.getAttr("id"));

                    la.onclick = function(e) {
                        console.log(tmp.getAttr("id"));
                        e.preventDefault();
                        tmp.setAttr("tooltip-label", $("#floor-label").val());
                        tmp.setAttr("tooltip-desc", $("#floor-desc").val());
                        $("#floor-label").addClass("hide");
                        $("#floor-desc").addClass("hide");
                        $("#label-save").addClass("hide");
                        checkEditLabel = 0;
                        $("#edit-label").removeClass("btn-success");
                        $("#edit-label").addClass("btn-default");
                    };
                    //$("#label-save").click(function(){  
                    //});
                } else if (floorDrawChecker === 1) {
                    checkEditLabel = 0;
                    removeFloorChecker = 0;
                    //alert("aho");
                } else {
                    saveLayout();
                    $("#sub-layout-id").val(tmp.getAttr("id"));
                    $("#venue-sub-container").css("display", "block");
                    $("#venue-main-container").css("display", "none");
                    $("#main-toolbar").css("display", "none");
                    $("#sub-toolbar").removeClass("hide");
                }
            }
        });
    });

    $("#show-floors").on('mousedown touchstart', function() {
        var poly = floorStage.find(".polygon");
        if ($("#show-floors span").hasClass("glyphicon-eye-open")) {
            $("#show-floors span").removeClass("glyphicon-eye-open");
            $("#show-floors span").addClass("glyphicon-eye-close");
            $("#show-floors").attr("title", "hide drawn floors");
            poly.each(function(ev) {
                ev.setOpacity(.3);
                coordImgLayer.draw();
            });
        } else {
            $("#show-floors span").addClass("glyphicon-eye-open");
            $("#show-floors span").removeClass("glyphicon-eye-close");
            $("#show-floors").attr("title", "show drawn floors");
            poly.each(function(ev) {
                ev.setOpacity(0);
                coordImgLayer.draw();
            });
        }
    });

    $("#coordSave").on('mousedown touchstart', function() {
        //canvasToJSON();
        //$("#save-layout").submit();
    });

    $("#venue-main-working-area").bind('contextmenu', function(e) {
        return false;
    });

    $("#save-floor").on('mousedown touchstart', function(e) {
        saveLayout();
        newOrReloadStage();
    });

    $("#upload-main-layout-bg").on('mousedown touchstart', function() {
        $("#main-layout-img").click();
    });
    /*------------reload canvas----------------------------*/
    function reload_stage() {
        var reloadData = $("#imgData").val();
        // create node using json string(reload the stage)
        var reloadStage = Kinetic.Node.create(reloadData, 'reload-venue-main-working-area');
        //array of polygon in the stage
        var poly = reloadStage.find('.polygon');
        var picture = reloadStage.find(".coordBG");
        //reload the image background
        var reloadTooltip = reloadStage.find(".tp");
        reloadTooltip.hide();
        reloadStage.draw();
        picture.each(function(e) {
            var imageObj = new Image();
            imageObj.onload = function() {
                e.setImage(imageObj);
                reloadStage.draw();
            };

            imageObj.src = $url + $("#img-url").val();
        });
        var reloadShowPoly = document.getElementById("reload-show-floors");
        reloadShowPoly.onmousedown = function() {
            if ($("#reload-show-floors span").hasClass("glyphicon-eye-open")) {
                $("#reload-show-floors span").removeClass("glyphicon-eye-open");
                $("#reload-show-floors span").addClass("glyphicon-eye-close");
                $("#reload-show-floors").attr("title", "hide drawn floors");
                poly.each(function(ev) {
                    ev.setOpacity(.3);
                    reloadStage.draw();
                });
            } else {
                $("#reload-show-floors span").addClass("glyphicon-eye-open");
                $("#reload-show-floors span").removeClass("glyphicon-eye-close");
                $("#reload-show-floors").attr("title", "show drawn floors");
                poly.each(function(ev) {
                    ev.setOpacity(0);
                    reloadStage.draw();
                });
            }
        };

        var reloadEditLabel = document.getElementById("reload-edit-label");
        var checkReloadEditLabel = 0;
        reloadEditLabel.onmousedown = function() {
            if (checkReloadEditLabel === 0) {
                checkReloadEditLabel = 1;
                $("#reload-edit-label").addClass("btn-success");
                $("#reload-edit-label").removeClass("btn-default");
                
            } else {
                checkReloadEditLabel = 0;
                $("#reload-edit-label").removeClass("btn-success");
                $("#reload-edit-label").addClass("btn-default");
            }
        };

        poly.on('mouseover touchstart', function(e) {
            var tmp = this;
            document.body.style.cursor = 'pointer';
            this.setOpacity(.3);
            reloadStage.draw();
            $("#reload-displayed-label").text(tmp.getAttr("tooltip-label"));
            $("#reload-displayed-desc").text(tmp.getAttr("tooltip-desc"));
            $("#reload-displayed-label").removeClass("hide");
            $("#reload-displayed-desc").removeClass("hide");
        });

        poly.on('mouseout touchend', function(e) {
            document.body.style.cursor = 'default';
            this.setOpacity(0);
            reloadTooltip.hide();
            reloadStage.draw();
            $("#reload-displayed-label").addClass("hide");
            $("#reload-displayed-desc").addClass("hide");
        });

        poly.on('mousedown touchstart', function(e) {
            var tmp = this;
            if (checkReloadEditLabel === 1) {
                 $("#reload-floor-label").removeClass("hide");
                    $("#reload-floor-desc").removeClass("hide");
                    $("#reload-label-save").removeClass("hide");
                    $("#reload-floor-label").val(tmp.getAttr("tooltip-label"));
                    $("#reload-floor-desc").val(tmp.getAttr("tooltip-desc"));
                    var la = document.getElementById("reload-label-save");
                    console.log(tmp.getAttr("id"));

                    la.onclick = function(e) {
                        console.log(tmp.getAttr("id"));
                        e.preventDefault();
                        tmp.setAttr("tooltip-label", $("#reload-floor-label").val());
                        tmp.setAttr("tooltip-desc", $("#reload-floor-desc").val());
                        $("#reload-floor-label").addClass("hide");
                        $("#reload-floor-desc").addClass("hide");
                        $("#reload-label-save").addClass("hide");                        
                        checkReloadEditLabel = 0;
                        $("#reload-edit-label").removeClass("btn-success");
                        $("#reload-edit-label").addClass("btn-default");
                    };
            }else if(removeFloorChecker === 1){
                tmp.remove();
                reloadStage.draw();
            } else {
                $("#reload-sub-layout-id").val(tmp.getAttr("id"));
                $("#sub-layout-id").val(tmp.getAttr("id"));
                getSubData();
                $("#reload-main-toolbar").addClass("hide");
            }

        });

        poly.on('mousemove', function(e) {
            var el = this;
            updateTooltip(reloadTooltip[0], e.pageX - $("#reload-venue-main-working-area").offset().left, e.pageY - $("#reload-venue-main-working-area").offset().top, el.getAttr("tooltip-label"));
            reloadStage.batchDraw();
        });
    }

    /*------------sub layout----------------------------*/
    var subStage = new Kinetic.Stage({
        container: "venue-sub-working-area",
        width: (window.innerWidth / 100) * 49,
        height: 420
    });

    var subLayer = new Kinetic.Layer({
        draggable: true
    });
    subLayer.setAttr("id", "subLayer");
    subStage.add(subLayer);
    var container = subStage.getContainer();
    var subTooltipLayer = new Kinetic.Layer();
    var subTooltip = new Kinetic.Label({
        opacity: 0.75,
        visible: false,
        listening: false
    });

    subTooltip.add(new Kinetic.Tag({
        fill: 'black',
        pointerDirection: 'down',
        pointerWidth: 10,
        pointerHeight: 10,
        lineJoin: 'round',
        shadowColor: 'black',
        shadowBlur: 10,
        shadowOffset: {x: 10, y: 10},
        shadowOpacity: 0.5
    }));

    subTooltip.add(new Kinetic.Text({
        text: '',
        fontFamily: 'Calibri',
        fontSize: 18,
        padding: 5,
        fill: 'white'
    }));

    subTooltipLayer.add(subTooltip);
    subStage.add(subTooltipLayer);

    var dragSrcEl = null;


    $("#img-con").on('mouseover touchstart', function(e) {
        $("#img-con").css("overflow-y", "scroll");
    });

    $("#reload-img-con").on('mouseover touchstart', function(e) {
        $("#reload-img-con").css("overflow-y", "scroll");
    });

    $("#img-con").on('mouseout touchend', function(e) {
        $("#img-con").css("overflow-y", "hidden");
    });

    $("#reload-img-con").on('mouseout touchend', function(e) {
        $("#reload-img-con").css("overflow-y", "hidden");
    });

    $("#save-back-layout").on('mousedown touchstart', function() {
        saveSubLayout();
        $("#sub-toolbar").addClass("hide");
        newOrReloadStage();
    });

    function saveSubLayout() {
        $("#subData").val(subCanvasToJSON());
        $.ajax({
            url: $url + 'save-sub-layout',
            type: 'post',
            data: {'ev-id': $('#view-event-calendar-popup #event-id').val(),
                'subData': $("#subData").val(), "sub-id": $("#sub-layout-id").val()}
        });
    }

    function subCanvasToJSON() {
        return subStage.toJSON();
    }
    /*-------------reload sub canvas------------*/
    function getSubData() {
        $.ajax({
            url: $url + 'sub-has-layout',
            type: 'post',
            data: {'ev-id': $('#view-event-calendar-popup #event-id').val(), 'sub-id': $("#reload-sub-layout-id").val()},
            success: function(data) {
                $("#reload-venue-main-container").css("display", "none");
                if (data === "0") {
                    subLayer.destroyChildren();
                    subLayer.draw();
                    $("#venue-sub-container").css("display", "block");
                    $("#sub-toolbar").removeClass("hide");
                } else {
                    $("#reload-sub-toolbar").removeClass("hide");
                    $("#reload-venue-sub-container").removeClass("hide");
                    $("#sub-toolbar").addClass("hide");
                }
            }
        });

        $.ajax({
            url: $url + "sub-reload-layout",
            type: "post",
            data: {'ev-id': $('#view-event-calendar-popup #event-id').val(), "sub-id": $("#reload-sub-layout-id").val()},
            dataType: "json",
            success: function(data) {
                $("#reload-subData").val(data);
                reload_sub_stage();
            }
        });
    }
    var reloadSubStage;
    var reloadSubLayer;// = new Kinetic.Layer();

    function reload_sub_stage() {
        var reloadSubData = $("#reload-subData").val();
        // create node using json string
        reloadSubStage = Kinetic.Node.create(reloadSubData, 'reload-venue-sub-working-area');
        //reloadSubStage.add(reloadSubLayer); 
        var picture = reloadSubStage.find(".subLayImg");
        reloadSubLayer = reloadSubStage.find("#subLayer")[0];
        reloadSubLayer.setAttr("draggable", true);
        reloadSubStage.add(reloadSubTooltipLayer);
        //reloadSubLayer = x.getLayer();
        //console.log(reloadSubLayer);
        picture.each(function(e) {
            var imageObj = new Image();
            imageObj.onload = function() {
                e.setImage(imageObj);
                reloadSubStage.draw();
            };
            imageObj.src = e.getAttr("src");
        });

        var reloadSubToolImg = document.querySelectorAll('#reload-tool-img-con img');
        [].forEach.call(reloadSubToolImg, function(col) {
            col.addEventListener('dragstart', function(e) {
                dragSrcEl = this;
            });
        });
        var con = reloadSubStage.getContainer();

        con.ondragover = function(e) {
            e.preventDefault(); //@important
        };
        //insert image to stage
        con.ondrop = function(e) {
            //console.log(reloadSubLayer);
            var image = new Kinetic.Image({
                draggable: true,
                x: e.pageX - $("#reload-venue-sub-working-area").offset().left,
                y: e.pageY - $("#reload-venue-sub-working-area").offset().top
            });

            reloadSubLayer.add(image);
            var reloadSubImgObj = new Image();
            reloadSubImgObj.src = dragSrcEl.src;
            reloadSubImgObj.onload = function() {
                image.setImage(reloadSubImgObj);
                reloadSubLayer.draw();
            };
            image.setAttr("name", "subLayImg");
            image.setAttr("src", dragSrcEl.src);
            updateSubLayout();
        };


    }

    var reloadSubTooltipLayer = new Kinetic.Layer();
    var reloadSubTooltip = new Kinetic.Label({
        opacity: 0.75,
        visible: false,
        listening: false
    });

    reloadSubTooltip.add(new Kinetic.Tag({
        fill: 'black',
        pointerDirection: 'down',
        pointerWidth: 10,
        pointerHeight: 10,
        lineJoin: 'round',
        shadowColor: 'black',
        shadowBlur: 10,
        shadowOffset: {x: 10, y: 10},
        shadowOpacity: 0.5
    }));

    reloadSubTooltip.add(new Kinetic.Text({
        text: '',
        fontFamily: 'Calibri',
        fontSize: 18,
        padding: 5,
        fill: 'white'
    }));

    reloadSubTooltipLayer.add(reloadSubTooltip);

    $("#update-back-layout").on('mousedown touchstart', function() {
        updateSubLayout();
        $("#reload-sub-toolbar").addClass("hide");
        $("#reload-venue-sub-container").addClass("hide");
        newOrReloadStage();
    });

    function updateSubLayout() {
        $("#reload-subData").val(reloadSubCanvasToJSON());
        $.ajax({
            url: $url + 'update-sub-layout',
            type: 'post',
            data: {'ev-id': $('#view-event-calendar-popup #event-id').val(),
                'subData': $("#reload-subData").val(), "sub-id": $("#reload-sub-layout-id").val()}
        });
    }



    function reloadSubCanvasToJSON() {
        return reloadSubStage.toJSON();
    }

    var ui = {
        stage: null,
        scale: 1,
        zoomFactor: 1.1,
        origin: {
            x: 0,
            y: 0
        },
        zoom: function(event) {
            //console.log(event.currentTarget.id);
            var con, stg;

            if (event.currentTarget.id === "reload-venue-sub-working-area") {
                con = $("#reload-venue-sub-working-area");
                stg = reloadSubStage;
            } else {
                con = $("#venue-sub-working-area");
                stg = subStage;
            }
            event.preventDefault();
            var evt = event.originalEvent,
                    mx = evt.clientX - con.offset().left /* - canvas.offsetLeft */
                    ,
                    my = evt.clientY - con.offset().top /* - canvas.offsetTop */
                    ,
                    wheel = evt.wheelDelta / 120; //n or -n
            var zoom = (ui.zoomFactor - (evt.wheelDelta < 0 ? 0.2 : 0));
            var newscale = ui.scale * zoom;
            ui.origin.x = mx / ui.scale + ui.origin.x - mx / newscale;
            ui.origin.y = my / ui.scale + ui.origin.y - my / newscale;

            stg.setOffset(ui.origin.x, ui.origin.y);
            stg.setScale(newscale);
            stg.draw();

            ui.scale *= zoom;
        }
    };

    $("#reload-venue-sub-working-area").on("mousewheel", ui.zoom);
    $("#venue-sub-working-area").on("mousewheel", ui.zoom);

    /*------------------*/
    $("#tool-type").change(function() {
        getTools($('#tool-type').val());
    });

    function getTools($toolVal) {
        $.ajax({
            url: $url + 'get-tools',
            type: 'post',
            data: {'tool-type': $toolVal},
            dataType: "json",
            success: function(data) {
                $("#img-con").text("");
                $("#img-con").append(data);
                updateTools();
            }, error: function(e) {
                console.log(e);
            }
        });
    }

    function updateTools() {
        var grp;
        function update(activeAnchor) {
            var group = activeAnchor.getParent();
            var topLeft = group.get('.topLeft')[0];
            var topRight = group.get('.topRight')[0];
            var bottomRight = group.get('.bottomRight')[0];
            var bottomLeft = group.get('.bottomLeft')[0];
            var rct = group.get('.rct')[0];

            var anchorX = activeAnchor.getX();
            var anchorY = activeAnchor.getY();

            // update anchor positions
            switch (activeAnchor.getName()) {
                case 'topLeft':
                    topRight.setY(anchorY);
                    bottomLeft.setX(anchorX);
                    break;
                case 'topRight':
                    topLeft.setY(anchorY);
                    bottomRight.setX(anchorX);
                    break;
                case 'bottomRight':
                    bottomLeft.setY(anchorY);
                    topRight.setX(anchorX);
                    break;
                case 'bottomLeft':
                    bottomRight.setY(anchorY);
                    topLeft.setX(anchorX);
                    break;
            }

            rct.setPosition(topLeft.getPosition());

            var width = topRight.getX() - topLeft.getX();
            var height = bottomLeft.getY() - topLeft.getY();
            if (width && height) {
                rct.setSize(width, height);
            }
        }

        function addAnchor(group, x, y, name) {
            var layer = group.getLayer();
            var anchor = new Kinetic.Circle({
                x: x,
                y: y,
                stroke: '#666',
                fill: '#ddd',
                strokeWidth: 2,
                radius: 8,
                name: name,
                draggable: true,
                dragOnTop: false
            });

            anchor.on('dragmove', function() {
                update(this);
                layer.draw();
            });
            anchor.on('mousedown touchstart', function() {
                group.setDraggable(false);
                this.moveToTop();
            });
            anchor.on('dragend', function() {
                group.setDraggable(true);
                layer.draw();
            });
            // add hover styling
            anchor.on('mouseover', function() {
                var layer = this.getLayer();
                document.body.style.cursor = 'pointer';
                this.setStrokeWidth(4);
                layer.draw();
            });
            anchor.on('mouseout', function() {
                var layer = this.getLayer();
                document.body.style.cursor = 'default';
                this.setStrokeWidth(2);
                layer.draw();
            });

            grp.add(anchor);
        }

        var subToolImg = document.querySelectorAll('#tool-img-con img');
        [].forEach.call(subToolImg, function(col) {
            col.addEventListener('dragstart', function(e) {
                dragSrcEl = this;
            });
        });

        container.addEventListener('dragover', function(e) {
            e.preventDefault(); //@important
        });
        //insert image to stage
        var rect, oPoint, checkOMDR = 0;
        container.onmousedown = function(e) {
            if (checkDrawRect === 1) {
                grp = new Kinetic.Group({
                    draggable: true
                });
                oPoint = originalPoint = {x: e.layerX, y: e.layerY};
                rect = new Kinetic.Rect({
                    draggable: false,
                    x: e.layerX,
                    y: e.layerY,
                    fill: '#FFF',
                    width: 2,
                    height: 3,
                    stroke: '#000',
                    strokeWidth: 5,
                    name: "rct"
                });
                //     subLayer.add(rect);
                grp.add(rect);
                subLayer.add(grp);
                grp.moveToBottom();
                addAnchor(grp, rect.getPosition().x, rect.getPosition().y, 'topLeft');
                addAnchor(grp, rect.getPosition().x + rect.getWidth(), rect.getPosition().y, 'topRight');
                addAnchor(grp, rect.getPosition().x, rect.getPosition().y + rect.getHeight(), 'bottomRight');
                addAnchor(grp, rect.getPosition().x + rect.getWidth(), rect.getPosition().y + rect.getHeight(), 'bottomLeft');
                checkOMDR = 1;
                $("#draw-rect").removeClass("btn-success");
                $("#draw-rect").addClass("btn-default");
                checkDrawRect = 0;
            }
                        grp.on('mousedown',function(e){
                var ms = this;
                console.log(ms);
                var group2 = ms.getParent();
                var topLeft = group2.get('.topLeft');
                var topRight = group2.get('.topRight');
                var bottomRight = group2.get('.bottomRight');
                var bottomLeft = group2.get('.bottomLeft');
                topLeft.show();
                topRight.show();
                bottomLeft.show();
                bottomRight.show();
                subLayer.draw();
            });

            grp.on('dblclick',function(e){
                var dbl = this;
                console.log(dbl);
                var group1 = dbl.getParent();
                var topLeft = group1.get('.topLeft');
                var topRight = group1.get('.topRight');
                var bottomRight = group1.get('.bottomRight');
                var bottomLeft = group1.get('.bottomLeft');
                //console.log(bottomLeft);
                topLeft.hide();
                topRight.hide();
                bottomLeft.hide();
                bottomRight.hide();
                subLayer.draw();
            });
            
        };
        container.onmouseup = function(e) {
            checkDrawRect = 0;
            checkOMDR = 0;
        };
        container.onmousemove = function(e) {
            if (checkOMDR === 1) {
                var p = rect.attrs,
                        w = e.layerX - p.x,
                        h = e.layerY - p.y;

                rect.setX(oPoint.x);
                rect.setY(oPoint.y);

                rect.setWidth(w);
                rect.setHeight(h);
                subLayer.draw();
            }
        };


        container.ondrop = function(e) {
            var tmp = this;
            var image = new Kinetic.Image({
                draggable: true,
                x: e.pageX - $("#venue-sub-working-area").offset().left,
                y: e.pageY - $("#venue-sub-working-area").offset().top,
                width: parseInt(dragSrcEl.getAttribute("data-width")),
                height: parseInt(dragSrcEl.getAttribute("data-height"))
            });

            //console.log(dragSrcEl.getAttribute("data-width") + ":"+ dragSrcEl.getAttribute("data-height"));
            image.setAttr("img-tooltip", dragSrcEl.getAttribute("data-tooltip"));
            subLayer.add(image);
            subLayer.draw();
            var subImgObj = new Image();
            subImgObj.src = dragSrcEl.src;
            subImgObj.onload = function() {
                image.setImage(subImgObj);
                subLayer.draw();
            };
            image.setAttr("name", "subLayImg");
            image.setAttr("src", dragSrcEl.src);

            image.on('mousemove', function(e) {
                var el = this;
                updateTooltip(subTooltip, e.pageX - $("#venue-sub-working-area").offset().left, e.pageY - $("#venue-sub-working-area").offset().top, el.getAttr("img-tooltip"));
                subTooltipLayer.batchDraw();
            });

            image.on('mouseout', function(e) {
                subTooltip.hide();
                subLayer.draw();
            });

            image.on('dragstart', function(e) {
                subTooltip.hide();
                subLayer.draw();
            });

            image.on('mousedown', function(e) {
                var tmp = this;
                if (checkRotate === 1) {
                    if($("#rotate-degrees").val() !== ""){
                        tmp.rotate((parseInt($("#rotate-degrees").val())/100));
                        subLayer.batchDraw();
                    }
                    
                }
            });

            image.on('mousedown touchstart', function() {
                var tmp = this;
                if (mTop === 1) {
                    this.moveToTop();
                } else if (mBottom === 1) {
                    this.moveToBottom();
                } else if (mUp === 1) {
                    this.moveUp();
                } else if (mDown === 1) {
                    this.moveDown();
                }else if(checkRemoveImg === 1){
                    tmp.remove();
                    subLayer.draw();
                }
            });
        };
    }

    $("#reload-tool-type").change(function(e) {
        $.ajax({
            url: $url + 'get-tools',
            type: 'post',
            data: {'tool-type': $('#reload-tool-type').val()},
            dataType: "json",
            success: function(data) {
                $("#reload-img-con").text("");
                $("#reload-img-con").append(data);
                updateSubLayout();
                reload_sub_stage();
            }
        });
    });

    $("#draw-rect").on('mousedown', function(e) {
        if (checkDrawRect === 0) {
            checkDrawRect = 1;
            checkRotate = 0;
            $(this).addClass("btn-success");
            $(this).removeClass("btn-default");
            $("#rotate-image").removeClass("btn-success");
            $("#rotate-image").addClass("btn-default");
        } else {
            checkDrawRect = 0;
            $(this).removeClass("btn-success");
            $(this).addClass("btn-default");
        }
    });

    $("#rotate-image").on('mousedown', function(e) {
        if (checkRotate === 0) {
            checkRotate = 1;
            checkDrawRect = 0;
            $(this).addClass("btn-success");
            $(this).removeClass("btn-default");
            $("#draw-rect").removeClass("btn-success");
            $("#draw-rect").addClass("btn-default");
            $("#rotate-degrees").val("180");
            $("#rotate-degrees").prop('disabled', false);
        } else {
            checkRotate = 0;
            $(this).removeClass("btn-success");
            $(this).addClass("btn-default");
            $("#rotate-degrees").val("");
            $("#rotate-degrees").prop('disabled', true);
        }
    });

    $("#move-to-top,#move-to-bottom,#move-up,#move-down").on('mousedown', function(e) {
        switch (this.id) {
            case "move-to-top":
                if(mTop === 1){
                    mTop = 0;
                    $("#move-to-top").removeClass("btn-success");
                    $("#move-to-top").addClass("btn-default");
                }else{
                    mTop = 1;
                    $("#move-to-top").addClass("btn-success");
                    $("#move-to-top").removeClass("btn-default");
                    $("#move-to-bottom").removeClass("btn-success");
                    $("#move-to-bottom").addClass("btn-default");
                    $("#move-up").removeClass("btn-success");
                    $("#move-up").addClass("btn-default");
                    $("#move-down").removeClass("btn-success");
                    $("#move-down").addClass("btn-default");
                    $("#draw-rect").removeClass("btn-success");
                    $("#draw-rect").addClass("btn-default");
                    checkDrawRect = 0;
                    mBottom = 0;
                    mUp = 0;
                    mDown = 0;
                }
                break;
            case "move-to-bottom":
                if(mBottom === 1){
                    mBottom = 0;
                    $("#move-to-bottom").removeClass("btn-success");
                    $("#move-to-bottom").addClass("btn-default");
                }else{
                    mBottom = 1;
                    $("#move-to-bottom").addClass("btn-success");
                    $("#move-to-bottom").removeClass("btn-default");
                    $("#move-to-top").removeClass("btn-success");
                    $("#move-to-top").addClass("btn-default");
                    $("#move-up").removeClass("btn-success");
                    $("#move-up").addClass("btn-default");
                    $("#move-down").removeClass("btn-success");
                    $("#move-down").addClass("btn-default");
                    $("#draw-rect").removeClass("btn-success");
                    $("#draw-rect").addClass("btn-default");
                    checkDrawRect = 0;
                    mTop = 0;
                    mUp = 0;
                    mDown = 0;
                }
                break;
            case "move-up":
                if(mUp === 1){
                    mUp = 0;
                    $("#move-up").removeClass("btn-success");
                    $("#move-up").addClass("btn-default");
                }else{
                    mUp = 1;
                    $("#move-up").addClass("btn-success");
                    $("#move-tup").removeClass("btn-default");
                    $("#move-to-top").removeClass("btn-success");
                    $("#move-to-top").addClass("btn-default");
                    $("#move-to-bottom").removeClass("btn-success");
                    $("#move-to-bottom").addClass("btn-default");
                    $("#move-down").removeClass("btn-success");
                    $("#move-down").addClass("btn-default");
                    $("#draw-rect").removeClass("btn-success");
                    $("#draw-rect").addClass("btn-default");
                    checkDrawRect = 0;
                    mBottom = 0;
                    mTop = 0;
                    mDown = 0;
                }
                break;
            case "move-down":
                if(mDown === 1){
                    mDown = 0;
                    $("#move-up").removeClass("btn-success");
                    $("#move-up").addClass("btn-default");
                }else{
                    mDown = 1;
                    $("#move-down").addClass("btn-success");
                    $("#move-down").removeClass("btn-default");
                    $("#move-to-top").removeClass("btn-success");
                    $("#move-to-top").addClass("btn-default");
                    $("#move-to-bottom").removeClass("btn-success");
                    $("#move-to-bottom").addClass("btn-default");
                    $("#move-up").removeClass("btn-success");
                    $("#move-up").addClass("btn-default");
                    $("#draw-rect").removeClass("btn-success");
                    $("#draw-rect").addClass("btn-default");
                    checkDrawRect = 0;
                    mBottom = 0;
                    mUp = 0;
                    mTop = 0;
                }
                break;
        }
    });
    
    $("#remove-img").on('mousedown touchstart',function(){
        checkRemoveImg = 1;
    });
    
    $("#cancel-remove-img").on('mousedown touchstart',function(){
        checkRemoveImg = 0;
    });
});